'use client';

import { useState, useEffect } from 'react';
import { useApp } from '@/contexts/AppContext';
import { useToast } from '@/components/Toast';
import { products, categories } from '@/lib/mockData';

export default function OrderPage() {
  const { state, dispatch } = useApp();
  const { showToast, ToastContainer } = useToast();
  const [selectedProducts, setSelectedProducts] = useState<any[]>([]);
  const [paymentMethod, setPaymentMethod] = useState('alipay');
  const [isProcessing, setIsProcessing] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    
    // 获取URL参数中的产品ID
    const urlParams = new URLSearchParams(window.location.search);
    const productId = urlParams.get('product');
    
    if (productId) {
      const product = products.find(p => p.id === productId);
      if (product) {
        setSelectedProducts([{ product, quantity: 1 }]);
      }
    } else {
      // 如果没有指定产品，使用购物车中的商品
      setSelectedProducts(state.cart);
    }
  }, [state.cart]);

  const totalAmount = selectedProducts.reduce((sum, item) => sum + (item.product.price * item.quantity), 0);

  const handlePayment = async () => {
    if (selectedProducts.length === 0) {
      showToast('请选择要购买的商品！', 'error');
      return;
    }

    setIsProcessing(true);

    // 模拟支付过程
    setTimeout(() => {
      // 为每个产品创建订单记录
      selectedProducts.forEach(item => {
        for (let i = 0; i < item.quantity; i++) {
          const orderId = `ORD_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
          const purchasedBox = {
            id: orderId,
            userId: state.user?.id || '1',
            productId: item.product.id,
            productName: item.product.name,
            productCategory: item.product.category,
            price: item.product.price,
            purchaseDate: new Date().toISOString(),
            isUnboxed: false,
            orderId: orderId,
            paymentMethod: paymentMethod,
            status: 'paid'
          };
          
          dispatch({ type: 'PURCHASE_BOX', payload: purchasedBox });
        }
      });

      // 清空购物车
      dispatch({ type: 'CLEAR_CART' });
      
      setIsProcessing(false);
      showToast('🎉 支付成功！盲盒已添加到您的收藏！', 'success');
      
      // 2秒后跳转到个人中心
      setTimeout(() => {
        window.location.href = '/profile';
      }, 2000);
    }, 2000);
  };

  if (!mounted) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-xl">加载中...</div>
      </div>
    );
  }

  if (selectedProducts.length === 0) {
    return (
      <div className="min-h-screen bg-gray-50 py-8">
        <div className="max-w-2xl mx-auto px-4">
          <div className="bg-white rounded-lg p-8 text-center">
            <div className="text-6xl mb-4">🛒</div>
            <h2 className="text-2xl font-bold text-gray-800 mb-4">购物车为空</h2>
            <p className="text-gray-600 mb-6">请先添加商品到购物车</p>
            <a href="/" className="bg-gradient-to-r from-yellow-400 to-orange-400 text-black font-bold py-3 px-8 rounded-lg hover:shadow-lg transition-shadow">
              🛍️ 去购物
            </a>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="min-h-screen bg-gray-50 py-8">
      <div className="max-w-4xl mx-auto px-4">
        {/* 页面标题 */}
        <div className="text-center mb-8">
          <h1 className="text-3xl font-bold text-gray-800 mb-2">确认订单</h1>
          <p className="text-gray-600">请确认您的订单信息并选择支付方式</p>
        </div>

        <div className="grid lg:grid-cols-3 gap-8">
          {/* 左侧：订单详情 */}
          <div className="lg:col-span-2">
            {/* 商品列表 */}
            <div className="bg-white rounded-lg p-6 shadow-sm mb-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4">订单商品</h2>
              <div className="space-y-4">
                {selectedProducts.map((item, index) => {
                  const category = categories.find(c => c.id === item.product.category);
                  return (
                    <div key={index} className="flex items-center space-x-4 p-4 border border-gray-200 rounded-lg">
                      <div className={`w-20 h-20 bg-gradient-to-br ${item.product.bgColor} rounded-lg flex items-center justify-center`}>
                        <span className="text-2xl">{category?.icon || '📦'}</span>
                      </div>
                      <div className="flex-1">
                        <h3 className="font-semibold text-gray-800">{item.product.name}</h3>
                        <p className="text-sm text-gray-600">{item.product.description}</p>
                        <div className="mt-2 flex items-center space-x-4">
                          <span className="text-sm text-gray-500">原价值: {item.product.originalValue}</span>
                          <span className="text-sm text-gray-500">数量: {item.quantity}</span>
                        </div>
                      </div>
                      <div className="text-right">
                        <div className="text-xl font-bold text-gray-800">¥{item.product.price}</div>
                        <div className="text-sm text-gray-500">单价</div>
                      </div>
                    </div>
                  );
                })}
              </div>
            </div>

            {/* 收货信息 */}
            <div className="bg-white rounded-lg p-6 shadow-sm mb-6">
              <h2 className="text-xl font-bold text-gray-800 mb-4">收货信息</h2>
              <div className="grid md:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">收货人</label>
                  <input 
                    type="text" 
                    defaultValue={state.user?.name || ''}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" 
                  />
                </div>
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-1">联系电话</label>
                  <input 
                    type="text" 
                    defaultValue={state.user?.phone || ''}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" 
                  />
                </div>
                <div className="md:col-span-2">
                  <label className="block text-sm font-medium text-gray-700 mb-1">收货地址</label>
                  <input 
                    type="text" 
                    placeholder="请输入详细地址"
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-orange-500 focus:border-orange-500" 
                  />
                </div>
              </div>
            </div>

            {/* 支付方式 */}
            <div className="bg-white rounded-lg p-6 shadow-sm">
              <h2 className="text-xl font-bold text-gray-800 mb-4">支付方式</h2>
              <div className="space-y-3">
                {[
                  { id: 'alipay', name: '支付宝', icon: '💙', desc: '推荐使用支付宝快捷支付' },
                  { id: 'wechat', name: '微信支付', icon: '💚', desc: '微信扫码支付' },
                  { id: 'unionpay', name: '银联支付', icon: '🏦', desc: '银行卡支付' }
                ].map(method => (
                  <label key={method.id} className="flex items-center p-3 border border-gray-200 rounded-lg cursor-pointer hover:bg-gray-50">
                    <input
                      type="radio"
                      name="payment"
                      value={method.id}
                      checked={paymentMethod === method.id}
                      onChange={(e) => setPaymentMethod(e.target.value)}
                      className="text-orange-500 focus:ring-orange-500"
                    />
                    <span className="ml-3 text-2xl">{method.icon}</span>
                    <div className="ml-3">
                      <div className="font-medium text-gray-800">{method.name}</div>
                      <div className="text-sm text-gray-600">{method.desc}</div>
                    </div>
                  </label>
                ))}
              </div>
            </div>
          </div>

          {/* 右侧：订单总结 */}
          <div className="lg:col-span-1">
            <div className="bg-white rounded-lg p-6 shadow-sm sticky top-8">
              <h2 className="text-xl font-bold text-gray-800 mb-4">订单总结</h2>
              
              <div className="space-y-3 mb-6">
                <div className="flex justify-between">
                  <span className="text-gray-600">商品总计</span>
                  <span className="font-medium">¥{totalAmount.toFixed(2)}</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">运费</span>
                  <span className="font-medium text-green-600">免费</span>
                </div>
                <div className="flex justify-between">
                  <span className="text-gray-600">优惠</span>
                  <span className="font-medium text-red-600">-¥0.00</span>
                </div>
                <hr className="border-gray-200" />
                <div className="flex justify-between text-lg font-bold">
                  <span>总计</span>
                  <span className="text-orange-600">¥{totalAmount.toFixed(2)}</span>
                </div>
              </div>

              <div className="space-y-3">
                <button
                  onClick={handlePayment}
                  disabled={isProcessing}
                  className={`w-full py-4 px-6 rounded-lg font-bold text-white transition-all ${
                    isProcessing
                      ? 'bg-gray-400 cursor-not-allowed'
                      : 'bg-gradient-to-r from-yellow-400 to-orange-400 text-black hover:shadow-lg'
                  }`}
                >
                  {isProcessing ? '🔄 处理中...' : `💳 立即支付 ¥${totalAmount.toFixed(2)}`}
                </button>
                
                <div className="text-xs text-gray-500 text-center">
                  点击支付即表示您同意我们的服务条款
                </div>
              </div>

              {/* 安全提示 */}
              <div className="mt-6 p-3 bg-gray-50 rounded-lg">
                <div className="flex items-center space-x-2 text-sm text-gray-600">
                  <span>🔒</span>
                  <span>SSL加密保护您的支付安全</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <ToastContainer />
    </div>
  );
}